<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Cache\Annotation\Cacheable;

/**
 * 用户拉黑
 */
class UserBlacklist extends Model
{
    protected $table = 'user_blacklist';

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function blackUserItem()
    {
        return $this->belongsTo(User::class, 'black_user_id', 'id');
    }

    /**
     * 拉黑
     */
    static function addRecord($userId = 0, $blackUserId = 0)
    {
        $record = self::check($userId, $blackUserId);
        if ($record) {
            $record->flag = 1;
            return $record->saveOrFail() ? 1 : 0;
        }
        $model = new self();
        $model->user_id = $userId;
        $model->black_user_id = $blackUserId;
        $model->flag = 1;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 查找拉黑记录
     */
    static function check($userId = 0, $blackUserId = 0)
    {
        $where = ['user_id' => $userId, 'black_user_id' => $blackUserId, 'flag' => 1];
        return self::where($where)->first();
    }

    /**
     * 拉黑
     */
    static function removeRecord($userId = 0, $blackUserId = 0)
    {
        $record = self::check($userId, $blackUserId);
        if (!$record) return false;
        $record->flag = 0;
        return $record->saveOrFail() ? 1 : 0;
    }

    /**
     * 获取拉黑列表
     */
    static function getList($userId = 0, $type = 'data')
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        if ($type == 'uid') {
            return self::where($where)->pluck('black_user_id')->toArray();
        }
        return self::where($where)->orderBy('id', 'desc')->get()->toArray();
    }

    /**
     * @Cacheable(prefix="be_black_list", ttl=60, listener="be_black_list")
     * @param $userId
     * @return array
     */
    public static function getBeBlackList($userId)
    {
        $where = ['black_user_id' => $userId, 'flag' => 1];
        return self::where($where)->pluck('user_id')->toArray();
    }
}
